<?php

namespace App\Http\Controllers\Wechat;

use App\Http\Controllers\Controller;
use App\Http\Controllers\ScoreRuleController;
use App\Models\Survey;
use App\Models\SurveyAnswer;
use App\Models\SurveyProblem;
use App\Models\SurveyReply;
use App\Validate\SurveyValidate;
use Exception;
use Illuminate\Support\Facades\DB;

/**
 * 问卷调查首页
 */
class SurveyController extends Controller
{
    // 自动验证
    public $validate = null;
    public $model = null;
    public $replyModel = null;
    public $answerModel = null;
    public $problemModel = null;
    public $score_type = 15;

    /**
     * 实例化问卷调查验证类
     * Survey constructor.
     */
    public function __construct()
    {
        parent::__construct();

        $this->validate = new SurveyValidate();
        $this->model = new Survey();
        $this->replyModel = new SurveyReply();
        $this->answerModel = new SurveyAnswer();
        $this->problemModel = new SurveyProblem();
    }

    /**
     * 问卷调查列表
     * @param token ：用户 token
     * @return \think\response\Json
     */
    public function lists()
    {

        $user_id = $this->request->user_info['id'];

        // 当前时间
        $time = date("Y-m-d H:i:s");

        $sur_id = $this->replyModel
            ->select("sur_id")
            ->where("user_id", $user_id)
            ->groupBy("sur_id")
            ->pluck('sur_id')
            ->toArray();

        // 获取数据
        $res = $this->model->select('id', 'survey_name', 'intro', 'start_time', 'end_time')
            ->where("is_play",  1)
            ->where("is_del", 1)
            ->where("start_time", "<=", $time)
            ->where("end_time", ">=", $time)
            //  ->whereNotIn("id",$sur_id)
            ->orderByDesc("id")
            ->get()
            ->toArray();

        $surveyed = []; //已答问卷
        $notsurvey = []; //未答问卷
        foreach ($res as $key => $val) {
            $res[$key]['intro'] = strip_tags($val['intro']);

            if (in_array($val['id'], $sur_id)) {
                $val['node'] = 1; //已答题
                $surveyed[] = $val;
            } else {
                $val['node'] = 2; //未答题
                $notsurvey[] = $val;
            }
        }
        $data = array_merge($notsurvey, $surveyed);


        //增加行为分析
        $appInviteCodeBehaviorModel = new  \App\Models\AppInviteCodeBehavior();
        $appInviteCodeBehaviorModel->add(17);

        // 反馈数据
        if ($res) {
            return $this->returnApi(200, "获取成功", true, $data);
        }
        return $this->returnApi(203, "暂无数据");
    }


    /**
     * 问卷调查详情
     * @param $id ：问卷详情id
     * @param token ：用户 token
     * @return \think\response\Json
     */
    public function detail()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('web_detail')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];

        // 当前时间
        $time = date("Y-m-d H:i:s");

        // 获取问卷调查是否存在
        $res = $this->model->select('id', 'survey_name', 'intro', 'start_time', 'end_time', 'create_time')
            ->where("is_play", 1)
            ->where("is_del", 1)
            ->where("start_time", "<=", $time)
            ->where("end_time", ">=", $time)
            ->find($this->request->id);

        // 数据不存在
        if (!$res) {
            return $this->returnApi(203, "数据不存在或已删除");
        } else {
            // 获取状态
            $status = Survey::getSurveyStatus($res["id"], $res["start_time"], $res["end_time"], $user_id);

            if ($status !== true) {
                return $this->returnApi(202, $status);
            }
        }

        // 获取所有问题
        $problem = $this->problemModel->select('id as pro_id', 'problem', 'type')
            ->where("sur_id", $this->request->id)
            ->orderBy("id")
            ->get()
            ->toArray();


        // 获取该问卷所有答案
        $answer = $this->answerModel->select('id as ans_id', 'answer', 'pro_id', 'reply_num')
            ->where("sur_id", $this->request->id)
            ->orderBy("id")
            ->get()
            ->toArray();

        // 追加问题入数据
        $res["problem"] = Survey::disSurveyData($problem, $answer);

        return $this->returnApi(200, "获取成功", true, $res);
    }


    /**
     * 用户提交问卷调查数据
     * @param token ：用户 token
     * @param $id ：问卷调查id
      //  * @param $answers ：提交答案   json  格式  [{"problem":"1","answer":"1"},{"problem":"2","answer":"3|4|5"}
     * @param $answers ：提交答案   json  格式  [{ 	"problem": "1", "answer": "1", 	"content": "" }]
     *      problem: 问题id ;
     *      answer 答案：多个 | 分隔；
     *      content：填空题答案
     * @return \think\response\Json
     */
    public function reply()
    {
        //增加验证场景进行验证
        if (!$this->validate->scene('apply')->check($this->request->all())) {
            return $this->returnApi(201,  $this->validate->getError());
        }

        $user_id = $this->request->user_info['id'];

        $answers =  json_decode($this->request->answers, true);

        // 获取问卷调查是否存在
        $res = Survey::select('id', 'survey_name', 'start_time', 'end_time')
            ->where("is_play", 1)
            ->where("is_del", 1)
            ->find($this->request->id);

        // 数据不存在
        if (empty($res)) return $this->returnApi(202, "数据不存在或已删除");

        // 获取状态与反馈
        $status = Survey::getSurveyStatus($res["id"], $res["start_time"], $res["end_time"], $user_id);
        if ($status !== true) {
            return $this->returnApi(202, $status);
        }

        //$count = $this->problemModel->where("sur_id", $this->request->id)->count();
        // if ($count !== count($answers)) return $this->returnApi(206, '请完整填写问卷问题');

        // 组装数据
        $data = [];
        $i = 0;

        $answer_arr = null; //合并答案id
        foreach ($answers as $v) {
            if (empty($v['answer']) && empty($v['content'])) {
                return $this->returnApi(206, '请完整填写问卷问题');
            }
            $data[$i]["sur_id"] =  $this->request->id;
            $data[$i]["pro_id"] = $v['problem'];
            $data[$i]["answer"] = $v['answer'];
            $data[$i]["content"] = $v['content'];
            $data[$i]["user_id"] = $user_id;
            $data[$i]["create_time"] = date('Y-m-d H:i:s');

            $answer = explode("|", $v['answer']);
            foreach ($answer as $k => $v) {
                if (empty($v)) {
                    continue; //去除空数组
                }
                $answer_arr[] = $v;
            }
            $i++;
        }

        DB::beginTransaction();
        try {
            //写入用户提交答案
            $this->replyModel->insert($data);

            //修改答案选择次数
            $this->answerModel->whereIn('id', $answer_arr)->increment('reply_num');

            //增加参与量
            $this->model->where("id", $this->request->id)->increment("reply_num");

            /*消息推送*/
            $system_id = $this->systemAdd('问卷调查', $this->request->user_info['id'], $this->request->user_info['account_id'], 21, $this->request->id, '感谢您参与问卷调查：【' . $res->survey_name . '】');
            //增加积分
            if (config('other.is_need_score') === true  && !empty($account_id)) {
                $scoreRuleObj = new ScoreRuleController();
                $score_status = $scoreRuleObj->checkScoreStatus($this->score_type, $user_id, $account_id);

                if ($score_status['code'] == 200) {
                    $scoreRuleObj->scoreChange($score_status, $user_id, $account_id, $system_id); //添加积分消息
                }
            }

            DB::commit();
            return $this->returnApi(200, "提交成功", true);
        } catch (\Exception $e) {
            DB::rollBack();
            return $this->returnApi(202, "提交失败");
        }
    }
}
